﻿using Sidvall.AuthorizationManager.Data;
using Sidvall.Serialization;
using Sidvall.Xml;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Sidvall.AuthorizationManager.Workflow
{
	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1053:StaticHolderTypesShouldNotHaveConstructors")]
	public class ExportWorkItemProvider
	{
		#region Public Members

		#region ExecuteAsync

		public static async Task ExecuteAsync(string filePath, IAuthorizationScope authorizationScope, bool includeResourceItems, bool includeUserItems, bool formatted)
		{
			var content = GetJsonContent(authorizationScope, includeResourceItems, includeUserItems, formatted);
			await Sidvall.SystemContext.Current.SystemStorageManager.WriteAllTextAsync(filePath, content).ConfigureAwait(false);
		}
		public static async Task ExecuteAsync(string filePath, string xmlNode, IAuthorizationScope authorizationScope, bool includeResourceItems, bool includeUserItems, bool formatted)
		{
			XDocument data;
			XElement root, element;
			string jsonContent, fileContent;

			if (!await Sidvall.SystemContext.Current.SystemStorageManager.FileExistsAsync(filePath).ConfigureAwait(false))
				return;
			jsonContent = GetJsonContent(authorizationScope, includeResourceItems, includeUserItems, formatted);
			fileContent = await Sidvall.SystemContext.Current.SystemStorageManager.ReadAllTextAsync(filePath).ConfigureAwait(false);
			data = System.Xml.Linq.XDocument.Parse(fileContent, LoadOptions.PreserveWhitespace);
			root = data.GetFirstDescendant("applicationSettings");
			element = (from o in root.Descendants("setting")
					   where ((string)o.Attribute("name")).Equals(xmlNode, System.StringComparison.OrdinalIgnoreCase)
					   select o).FirstOrDefault();
			if (element == null)
				return;
			element = element.GetFirstDescendant("value");
			if (element == null)
				return;
			element.Value = jsonContent;
			using (var stream = new System.IO.MemoryStream())
			{
				using (var reader = new System.IO.StreamReader(stream))
				{
					data.Save(stream);
					stream.Position = 0;
					fileContent = reader.ReadToEnd();
				}
			}
			await Sidvall.SystemContext.Current.SystemStorageManager.WriteAllTextAsync(filePath, fileContent).ConfigureAwait(false);
		}

		#endregion
		#region GetJonContent

		public static string GetJsonContent(IAuthorizationScope authorizationScope, bool includeResourceItems, bool includeUserItems, bool formatted)
		{
			var item = AuthorizationScopeItemManager.CreateNewFromAuthorizationScope(authorizationScope, includeResourceItems, includeUserItems);
			var settings = new SerializerSettings();
			if (formatted)
				settings.Formatting = Formatting.Indented;
			return Sidvall.Serialization.SerializerManager.Current.SerializeObject(item, settings);
		}

		#endregion

		#endregion
	}
}
